<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * @mixin think\Model
 */
class Menu extends Model
{

    // 获取菜单列表
    public function getMenuTree(int $pid=0, $child_str='child', $extends=[]) {
        $menuList = $this
            ->field('id,pid,lv,title,icon,href,target,sort,status,create_time')
            ->where(['status'=>'on','is_menu'=>1])
            ->order('lv, sort asc')
            ->cache('menu_tree')
            ->select();
        $menuList = $this->buildMenuChild($pid, $menuList, $child_str, $extends);
        return $menuList;
    }

    // 获取菜单列表
    public function getMenuTreeAll(int $pid=0, $child_str='child', $extends=[]) {
        $menuList = $this
            ->field('id,pid,lv,title,icon,href,target,sort,status,create_time')
            ->order('lv, sort asc')
            ->cache('menu_tree_all')
            ->select();
        $menuList = $this->buildMenuChild($pid, $menuList, $child_str, $extends);
        return $menuList;
    }

    //递归获取子菜单
    private function buildMenuChild($pid, $menuList, $child_str='children', $extends=[]) {
        $treeList = [];
        foreach ($menuList as $v) {
            foreach ($extends as $ka => $va) {
                $v[$ka] = $va;
            }
            if ($pid == $v['pid']) {
                $node = $v;
                $child = $this->buildMenuChild($v['id'], $menuList, $child_str);
                if (!empty($child)) {
                    $node[$child_str] = $child;
                }
                // todo 后续此处加上用户的权限判断
                $treeList[] = $node;
            }
        }
        return $treeList;
    }

}
